<template>
  <div class="ai-solution-view">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">AI智能解题</h1>
      <p class="page-subtitle">让AI帮你解决公考难题</p>
    </div>

    <!-- 解题区域 -->
    <div class="solution-section">
      <!-- 题目输入 -->
      <div class="question-input-section">
        <el-card class="input-card">
          <template #header>
            <div class="card-header">
              <span>输入题目</span>
              <div class="upload-options">
                <el-button type="primary" size="small" @click="showUploadModal = true">上传图片</el-button>
                <el-button type="default" size="small" @click="showCameraModal = true">拍照识别</el-button>
              </div>
            </div>
          </template>
          <el-input
            v-model="questionText"
            type="textarea"
            :rows="8"
            placeholder="请输入题目内容，或使用上方按钮上传题目图片..."
            class="question-textarea"
          />
          <div class="input-actions">
            <el-select v-model="questionType" placeholder="题目类型" class="type-select">
              <el-option label="自动识别" value="auto" />
              <el-option label="单选题" value="single_choice" />
              <el-option label="多选题" value="multiple_choice" />
              <el-option label="判断题" value="true_false" />
              <el-option label="填空题" value="blank_filling" />
              <el-option label="简答题" value="short_answer" />
            </el-select>
            <el-button type="primary" class="solve-button" @click="solveQuestion" :loading="isSolving">
              <span v-if="!isSolving">AI解题</span>
              <span v-else>正在进入解题界面...</span>
            </el-button>
          </div>
        </el-card>
      </div>

      <!-- 历史记录 -->
      <div class="history-section">
        <el-card class="history-card">
          <template #header>
            <div class="card-header">
              <span>解题历史</span>
              <el-button type="text" size="small" @click="clearHistory">清空历史</el-button>
            </div>
          </template>
          <ConversationHistoryComponent @load-conversation="loadHistoryConversation" />
        </el-card>
      </div>
    </div>

    <!-- 上传图片模态框 -->
    <el-dialog v-model="showUploadModal" title="上传题目图片" width="600px">
      <el-upload
        drag
        action=""
        multiple
        :before-upload="handleUpload"
        :show-file-list="false"
        class="upload-dragger"
      >
        <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
        <div class="el-upload__text">
          拖拽文件到此处，或<em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          支持jpg、jpeg、png格式，单个文件不超过10MB
        </div>
      </el-upload>
    </el-dialog>

    <!-- 拍照识别模态框 -->
    <el-dialog v-model="showCameraModal" title="拍照识别题目" width="80%" :fullscreen="isMobile">
      <div class="camera-container">
        <div ref="cameraContainer" class="camera-feed-container">
          <video ref="videoElement" autoplay playsinline></video>
          <canvas ref="canvasElement" style="display: none;"></canvas>
        </div>
      </div>
      <template #footer>
        <el-button @click="closeCamera">取消</el-button>
        <el-button type="primary" @click="takePhoto">拍照识别</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { UploadFilled } from '@element-plus/icons-vue';
import ConversationHistoryComponent from '@/components/ConversationHistory.vue';
import { useAiSolverStore, type ConversationHistory } from '@/store/ai-solver';

// 路由
const router = useRouter();

// AI解题存储
const aiSolverStore = useAiSolverStore();

// 题目输入
const questionText = ref('');
const questionType = ref('auto');
const isSolving = ref(false);

// 响应式数据
const videoElement = ref<HTMLVideoElement | null>(null);
const canvasElement = ref<HTMLCanvasElement | null>(null);
const cameraContainer = ref<HTMLDivElement | null>(null);

// 页面状态
const isMobile = ref(false);
const showUploadModal = ref(false);
const showCameraModal = ref(false);

// 历史记录（暂时未使用，保留以备将来使用）
// const solutionHistory = ref<any[]>([
//   {
//     question: '根据《中华人民共和国民法典》规定，自然人下落不明满（ ）年的，利害关系人可以向人民法院申请宣告该自然人为失踪人。\nA. 1年\nB. 2年\nC. 3年\nD. 4年',
//     solution: {
//       answer: 'B. 2年',
//       explanation: '《中华人民共和国民法典》第四十条规定，自然人下落不明满二年的，利害关系人可以向人民法院申请宣告该自然人为失踪人。',
//       knowledgePoints: ['民法典', '宣告失踪', '法律常识'],
//       similarQuestions: [
//         { id: 1, preview: '宣告死亡的法定条件是什么？' },
//         { id: 2, preview: '失踪人的财产如何管理？' }
//       ]
//     },
//     timestamp: new Date(Date.now() - 2 * 60 * 60 * 1000)
//   },
//   {
//     question: '2024年全国两会期间，政府工作报告指出，要坚持稳中求进工作总基调，完整、准确、全面贯彻新发展理念，加快构建新发展格局，着力推动高质量发展。2024年我国国内生产总值增长预期目标为（ ）左右。\nA. 5%\nB. 6%\nC. 5.5%\nD. 4.5%',
//     solution: {
//       answer: 'A. 5%',
//       explanation: '2024年政府工作报告指出，2024年我国国内生产总值增长预期目标为5%左右。',
//       knowledgePoints: ['时政热点', '政府工作报告', '经济增长'],
//       similarQuestions: [
//         { id: 3, preview: '2024年政府工作报告的主要内容有哪些？' },
//         { id: 4, preview: '新发展理念包括哪些内容？' }
//       ]
//     },
//     timestamp: new Date(Date.now() - 5 * 60 * 60 * 1000)
//   },
//   {
//     question: '某商场进行促销活动，一件上衣原价200元，现在打八折销售，请问现价是多少元？\nA. 160元\nB. 180元\nC. 140元\nD. 120元',
//     solution: {
//       answer: 'A. 160元',
//       explanation: '打八折意味着现价是原价的80%，所以现价=200×80%=160元。',
//       knowledgePoints: ['数量关系', '折扣计算', '百分数'],
//       similarQuestions: [
//         { id: 5, preview: '如果一件商品先涨价10%，再降价10%，最终价格是多少？' },
//         { id: 6, preview: '某商品打七五折后售价为150元，原价是多少？' }
//       ]
//     },
//     timestamp: new Date(Date.now() - 24 * 60 * 60 * 1000)
//   }
// ]);

// 处理文本输入解题
const solveQuestion = () => {
  if (!questionText.value.trim()) {
    ElMessage.warning('请输入题目内容');
    return;
  }

  isSolving.value = true;

  // 模拟加载延迟
  setTimeout(() => {
    // 跳转到AI聊天界面，并传递题目文本
    router.push({
      path: '/ai-chat',
      query: { text: questionText.value }
    });
    
    isSolving.value = false;
  }, 800);
};

// 处理文件上传
const handleUpload = (file: File) => {
  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('请上传图片文件');
    return false;
  }

  // 检查文件大小（10MB限制）
  if (file.size > 10 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过10MB');
    return false;
  }

  // 读取图片文件并跳转到聊天页面
  const reader = new FileReader();
  reader.onload = (e) => {
    const imageUrl = e.target?.result as string;
    
    // 关闭上传模态框
    showUploadModal.value = false;
    
    // 跳转到AI聊天界面，并传递图片数据
    router.push({
      path: '/ai-chat',
      query: { imageUrl }
    });
  };
  reader.readAsDataURL(file);
  
  return false; // 阻止默认上传
};

// 拍照识别
const takePhoto = () => {
  if (videoElement.value && canvasElement.value) {
    const canvas = canvasElement.value;
    const video = videoElement.value;
    
    // 设置canvas尺寸与视频一致
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    
    // 绘制当前视频帧到canvas
    const ctx = canvas.getContext('2d');
    if (ctx) {
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
      
      // 获取图片数据URL
      const imageUrl = canvas.toDataURL('image/jpeg');
      
      // 关闭相机模态框
      closeCamera();
      
      // 跳转到AI聊天界面，并传递图片数据
      router.push({
        path: '/ai-chat',
        query: { imageUrl }
      });
    }
  }
};

// 关闭相机
const closeCamera = () => {
  if (videoElement.value && videoElement.value.srcObject) {
    const stream = videoElement.value.srcObject as MediaStream;
    const tracks = stream.getTracks();
    tracks.forEach(track => track.stop());
  }
  showCameraModal.value = false;
};

// 打开相机模态框
const openCameraModal = () => {
  checkIfMobile();
  showCameraModal.value = true;
  
  // 等待模态框渲染完成后再初始化相机
  setTimeout(async () => {
    try {
      if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        const stream = await navigator.mediaDevices.getUserMedia({
          video: {
            facingMode: 'environment' // 优先使用后置摄像头
          }
        });
        
        if (videoElement.value && cameraContainer.value) {
          videoElement.value.srcObject = stream;
          // 设置视频尺寸以适应容器
          const setVideoDimensions = () => {
            if (videoElement.value) {
              videoElement.value.style.width = '100%';
              videoElement.value.style.height = 'auto';
            }
          };
          
          videoElement.value.onloadedmetadata = setVideoDimensions;
          window.addEventListener('resize', setVideoDimensions);
        }
      }
    } catch (error) {
      ElMessage.error('无法访问摄像头，请确保已授予相机权限');
      console.error('Camera error:', error);
      showCameraModal.value = false;
    }
  }, 300);
};

// 监听相机模态框打开
watch(showCameraModal, (newValue) => {
  if (newValue) {
    openCameraModal();
  }
});

// 加载历史对话
const loadHistoryConversation = (conversation: ConversationHistory) => {
  questionText.value = conversation.question;
  
  // 跳转到AI聊天界面，并传递历史题目
  router.push({
    path: '/ai-chat',
    query: { 
      text: conversation.question,
      isHistory: 'true',
      imageUrl: conversation.imageUrl || ''
    }
  });
};

// 复制历史解决方案（暂时未使用，保留以备将来使用）
// const copyHistorySolution = (index: number) => {
//   const history = solutionHistory.value[index];
//   navigator.clipboard.writeText(history.solution.answer + '\n\n' + history.solution.explanation);
//   ElMessage.success('答案已复制到剪贴板');
// };

// 删除历史记录（暂时未使用，保留以备将来使用）
// const deleteHistoryItem = (index: number) => {
//   solutionHistory.value.splice(index, 1);
//   ElMessage.success('历史记录已删除');
// };

// 清空历史记录
const clearHistory = () => {
  aiSolverStore.clearHistory();
  ElMessage.success('历史记录已清空');
};

// 预览题目（暂时未使用，保留以备将来使用）
// const previewQuestion = (question: string) => {
//   return question.length > 50 ? question.substring(0, 50) + '...' : question;
// };

// 格式化时间（暂时未使用，保留以备将来使用）
// const formatTime = (time: Date) => {
//   return new Date(time).toLocaleString('zh-CN');
// };

// 检查是否为移动端
const checkIfMobile = () => {
  const isMobileDevice = window.innerWidth <= 768;
  isMobile.value = isMobileDevice;
};

// 生命周期钩子
onMounted(() => {
  checkIfMobile();
  window.addEventListener('resize', checkIfMobile);
});

onUnmounted(() => {
  window.removeEventListener('resize', checkIfMobile);
  // 确保关闭相机
  if (videoElement.value && videoElement.value.srcObject) {
    const stream = videoElement.value.srcObject as MediaStream;
    const tracks = stream.getTracks();
    tracks.forEach(track => track.stop());
  }
});

// 导入必要的API
import { watch } from 'vue';
</script>

<style lang="scss" scoped>
.ai-solution-view {
  padding: 20px;
  padding-top: 100px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  text-align: center;
  margin-bottom: 40px;
  padding: 40px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  color: white;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);

  .page-title {
    font-size: 2.5rem;
    font-weight: 700;
    margin-bottom: 10px;
  }

  .page-subtitle {
    font-size: 1.2rem;
    opacity: 0.9;
  }
}

.solution-section {
  display: flex;
  flex-direction: column;
  gap: 20px;

  .question-input-section {
    .input-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .upload-options {
        display: flex;
        gap: 10px;
      }

      .question-textarea {
        margin-bottom: 15px;
      }

      .input-actions {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .type-select {
          min-width: 150px;
        }

        .solve-button {
          min-width: 120px;
        }
      }
    }
  }

  .history-section {
    .history-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .history-item {
        padding: 10px;
        background-color: #f9fafb;
        border-radius: 6px;
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
          background-color: #f3f4f6;
        }

        .history-question-preview {
          font-size: 14px;
          color: #4b5563;
          margin-bottom: 5px;
        }

        .history-actions {
          display: flex;
          justify-content: flex-end;
          gap: 5px;
        }
      }
    }
  }
}

.camera-container {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f9fafb;
  border-radius: 8px;
  margin-bottom: 20px;
}

.camera-feed-container {
  width: 100%;
  max-width: 500px;
  aspect-ratio: 4/3;
  overflow: hidden;
  background-color: #000;
  border-radius: 8px;
}

.camera-feed-container video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

// 响应式设计
@media (max-width: 768px) {
  .ai-solution-view {
    padding-top: 80px;
  }

  .page-header {
    padding: 30px 15px;
    
    .page-title {
      font-size: 2rem;
    }
    
    .page-subtitle {
      font-size: 1rem;
    }
  }

  .camera-feed-container {
    width: 100%;
    aspect-ratio: 9/16; // 适配手机屏幕比例
  }
}
</style>